package cn.dapeng.features;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Atomic_T01 {

    static long n = 0l;

    public static void m1() throws Exception {

        Thread[] t = new Thread[100];
        for (int i = 0; i < t.length; i++) {
            t[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    synchronized (Atomic_T01.class) {
                        n++;
                    }
                }
            });
            t[i].start();
            t[i].join();
        }

        System.out.println("sum ::: " + n);
    }

    public static void m2() throws Exception {
        Thread[] t = new Thread[100];
        CountDownLatch latch = new CountDownLatch(t.length);
        for (int i = 0; i < t.length; i++) {
            t[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    synchronized (Atomic_T01.class) {
                        n++;
                    }
                }

                latch.countDown();
            });
            t[i].start();
        }
        latch.await();
        System.out.println("sum ::: " + n);
    }

    public static void m3() throws Exception {
        AtomicInteger ai = new AtomicInteger(0);

        Thread[] t = new Thread[100];
        CountDownLatch latch = new CountDownLatch(t.length);
        for (int i = 0; i < t.length; i++) {
            t[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    ai.incrementAndGet();
                }
                latch.countDown();
            });
            t[i].start();
        }
        latch.await();
        System.out.println("sum ::: " + ai.get());
    }

    public static void main(String[] args) throws Exception {
        //m1();
        //m2();
        m3();
    }
}
